package swing.customComp;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.geom.Rectangle2D;

public class AutoWidthTextField extends JTextField {

    public AutoWidthTextField() {
        super();
        this.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                FontMetrics myMetrics = new FontMetrics(getFont()) {};
                Rectangle2D boundsOfString = myMetrics.getStringBounds(getText(), null);
                int width = (int) boundsOfString.getWidth();
                if (width > getWidth()-40)
                    setSize(width, getHeight());
            }

            @Override
            public void removeUpdate(DocumentEvent e) {

            }

            @Override
            public void changedUpdate(DocumentEvent e) {

            }
        });
    }
}
